const express = require('express');
const router = express.Router();
const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken')
const Admin = require('../../models/admin')

//初始化管理员
router.post('/init',async (req,res) => {
    const data = await Admin.create(req.body)
    res.send(data)
})

//登录处理
router.post('/',async (req,res) => {
    const {username,password} = req.body

    //登录校验
    if(!username) return res.status(500).send({ message:"用户名不能为空！！" })
    if(!password) return res.status(500).send({ message:"密码不能为空！！" })
    let adminuser = await Admin.findOne({username}).lean()
    if (!adminuser) return res.status(422).send({ message:"用户不存在！！" })
    const isVal = bcrypt.compareSync(password,adminuser.password)
    if(!isVal) return res.status(422).send({ message:"密码错误！！" })

    adminuser.password = '******'

    //存储token的数据
    let data = {}
    data.id = adminuser._id
    data.ctime = parseInt(new Date().getTime() / 1000)//创建时间、当前时间
    data.expiresIn = 60*60*24 //过期时间/1天

    //生成token
    const token = jwt.sign(data,req.app.get('token'))

    res.send({
        adminuser,
        token
    })
})

module.exports = router;